<template>
  <div class="pipe-standard-container">
    <!-- 搜索 + 操作按钮区域 -->
    <div class="search-action-bar">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="部件名称">
          <el-input
            v-model="searchForm.pipe_name"
            placeholder="请输入部件名称"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="管道规格">
          <el-input
            v-model="searchForm.pipe_specification"
            placeholder="请输入管道规格"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="管道材料">
          <el-input
            v-model="searchForm.pipe_material"
            placeholder="请输入管道材料"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格展示区域（增加 loading 状态） -->
    <el-table
      :data="tableData"
      style="width: 100%"
      max-height="500"
      border
      stripe
      v-loading="tableLoading"
      element-loading-text="数据加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.8)"
    >
      <!-- 逐列校验 prop 与实际接口字段匹配，这里假设接口返回字段为驼峰（如 pipeStaId），可根据真实返回调整 -->
      <el-table-column prop="pipeStaId" label="管材标准ID" width="120" />
      <el-table-column prop="pipeWarId" label="所属预警管理ID" width="150" />
      <el-table-column prop="pipeName" label="部件名称" width="180" />
      <el-table-column prop="pipeSpecification" label="管道规格" width="150" />
      <el-table-column prop="pipeValue" label="管道厚度标准值" width="150" />
      <el-table-column prop="pipeMaterial" label="管道材料" width="120" />
      <el-table-column prop="pipeNumber" label="管排片数" width="120" />
      <el-table-column
        prop="pipeRemark"
        label="备注信息"
        width="200"
        show-overflow-tooltip
      />
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        :formatter="formatDate"
      />
      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="180"
        :formatter="formatDate"
      />
      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">
            修改
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-bar">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageDto.page"
        :page-sizes="[5, 10, 20, 30, 50]"
        :page-size="pageDto.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      title="新增/修改管道信息"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <el-form :model="form" :rules="rules" label-width="120px" ref="formRef">
        <el-form-item label="管材标准ID" prop="pipeStaId">
          <el-input v-model.number="form.pipeStaId" disabled />
        </el-form-item>
        <!-- 所属预警管理ID（核心优化：按钮居右 + 关联名称展示） -->
        <el-form-item label="所属预警管理ID" prop="pipeWarId">
  <div class="war-id-row">
    <!-- 1. 左侧：输入框 -->
    <el-input
      v-model.number="form.pipeWarId"
      placeholder="输入ID或点击选择"
      style="flex: 1; margin-right: 8px"
    />

    <!-- 2. 中间：关联预警名称 -->
    <span
      v-if="relatedWarName"
      class="related-war-name"
      style="margin: 0 8px; line-height: 32px"
    >
      {{ relatedWarName }}
    </span>

    <!-- 3. 右侧：固定选择按钮 -->
    <el-button
      type="primary"
      icon="el-icon-search"
      style="min-width: 100px"
      @click="openWarningSelector"
    >
      选择预警
    </el-button>
  </div>
</el-form-item>
        <el-form-item label="部件名称" prop="pipeName">
          <el-input v-model="form.pipeName" />
        </el-form-item>
        <el-form-item label="管道规格" prop="pipeSpecification">
          <el-input v-model="form.pipeSpecification" />
        </el-form-item>
        <el-form-item label="管道厚度标准值" prop="pipeValue">
          <el-input v-model.number="form.pipeValue" disabled />
        </el-form-item>
        <el-form-item label="管道材料" prop="pipeMaterial">
          <el-input v-model="form.pipeMaterial" />
        </el-form-item>
        <el-form-item label="管排片数" prop="pipeNumber">
          <el-input v-model.number="form.pipeNumber" />
        </el-form-item>
        <el-form-item label="备注信息">
          <el-input type="textarea" v-model="form.pipeRemark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="success" @click="handleSave">确定</el-button>
      </div>
    </el-dialog>

    <!-- 选择器弹窗 -->
    <PipeWarningSelector
      :visible.sync="warningSelectorVisible"
      @selected="handleWarningSelected"
    />

    <!-- 删除确认弹窗 -->
    <el-dialog title="删除确认" :visible.sync="deleteVisible" width="30%">
      <p>确定要删除该记录吗？此操作不可逆</p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deleteVisible = false"
          >取消</el-button
        >
        <el-button type="danger" @click="confirmDelete">确定删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import PipeWarningSelector from "../TableOrForms/PipeWarningSelector.vue";

export default {
  name: "PipeStandard",
  components: {
    PipeWarningSelector,
  },
  data() {
    return {
      searchForm: {},
      pageDto: {
        page: 1,
        size: 10,
        pipeStandard: {},
      },
      total: 0,
      tableData: [],
      dialogVisible: false,
      deleteVisible: false,
      deleteId: null,
      form: {},
      rules: {
        pipeWarId: [
          { required: true, message: "请输入所属预警管理ID", trigger: "blur" },
          { type: "number", message: "请输入数字值", trigger: "blur" },
        ],
        pipeName: [
          { required: true, message: "请输入部件名称", trigger: "blur" },
        ],
        pipeSpecification: [
          { required: true, message: "请输入管道规格", trigger: "blur" },
        ],
        pipeMaterial: [
          { required: true, message: "请输入管道材料", trigger: "blur" },
        ],
        pipeNumber: [
          { required: true, message: "请输入管排片数", trigger: "blur" },
          { type: "number", message: "请输入数字值", trigger: "blur" },
        ],
      },
      tableLoading: false,
      warningSelectorVisible: false,
      relatedWarName:"",
    };
  },
  methods: {
    formatDate(row, column) {
      const date = row[column.property];
      return date ? new Date(date).toLocaleString() : "";
    },
    handleSizeChange(val) {
      this.pageDto.size = val;
      this.queryByPage();
    },
    handleCurrentChange(val) {
      this.pageDto.page = val;
      this.queryByPage();
    },
    handleQuery() {
      this.pageDto.pipeStandard.pipeName = this.searchForm.pipe_name;
      this.pageDto.pipeStandard.pipeSpecification =
      this.searchForm.pipe_specification;
      this.pageDto.pipeStandard.pipeMaterial = this.searchForm.pipe_material;
      this.pageDto.page = 1;
      this.queryByPage();
    },
    resetQuery() {
      this.searchForm = {};
      this.pageDto = { page: 1, size: 10, pipeStandard: {} };
      this.queryByPage();
    },
    handleAdd() {
      this.form = {};
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.form = { ...row };
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.deleteId = row.pipeStaId;
      this.deleteVisible = true;
    },
    confirmDelete() {
      this.$api.pipeStandardApi
        .deleteById({ pipeStaId: this.deleteId })
        .then((res) => {
          if (res.data.code === 1) {
            this.$notify.success({
              title: "成功",
              message: res.data.msg || "删除成功！",
            });
            this.deleteVisible = false;
            this.queryByPage();
          } else {
            this.$notify.error({
              title: "错误",
              message: res.data.msg || "删除失败",
            });
          }
        })
        .catch(() => {
          this.$notify.error({
            title: "错误",
            message: "网络异常，请重试",
          });
        });
    },
    handleSave() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const isEdit = !!this.form.pipeStaId;
          const apiMethod = isEdit
            ? this.$api.pipeStandardApi.edit
            : this.$api.pipeStandardApi.add;
          apiMethod(this.form)
            .then((res) => {
              if (res.data.code === 1) {
                this.$notify.success({
                  title: "成功",
                  message: isEdit ? "修改成功！" : "新增成功！",
                });
                this.dialogVisible = false;
                this.queryByPage();
              } else {
                this.$notify.error({
                  title: "错误",
                  message: res.data.msg || (isEdit ? "修改失败" : "新增失败"),
                });
              }
            })
            .catch(() => {
              this.$notify.error({
                title: "错误",
                message: "网络异常，请重试",
              });
            });
        }
      });
    },
    queryByPage() {
      this.tableLoading = true;
      this.$api.pipeStandardApi
        .queryByPage(this.pageDto)
        .then((res) => {
          if (res.data.code === 1) {
            // 强制触发响应式更新
            this.tableData = res.data.data.list;
            this.total = res.data.data.total;
          } else {
            this.$notify.error({
              title: "错误",
              message: res.data.msg || "查询失败",
            });
          }
        })
        .catch(() => {
          this.$notify.error({
            title: "错误",
            message: "网络异常，请重试",
          });
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    // 打开选择器
    openWarningSelector() {
      this.warningSelectorVisible = true;
    },
    // 接收选择器传回的数据
    handleWarningSelected(pipeWarId, warName) {
      this.form.pipeWarId = pipeWarId;
      this.relatedWarName = warName;
    },
  },
  mounted() {
    this.queryByPage();
  },
};
</script>

<style scoped>
/* 原有样式保持不变 */
.pipe-standard-container {
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
  min-height: calc(100vh - 40px);
}

.search-action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.search-input {
  width: 180px !important;
}

.pagination-bar {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}

.el-button {
  transition: all 0.3s ease;
}

.el-button:hover {
  transform: scale(1.05);
}

.el-dialog__body {
  padding: 20px;
  line-height: 1.6;
}

.el-table {
  width: 100% !important;
  table-layout: fixed;
  overflow: auto;
}

.el-table__column--pipe_sta_id {
  width: 120px;
}
.el-table__column--pipe_war_id {
  width: 150px;
}
.el-table__column--pipe_name {
  width: 180px;
}
.el-table__column--pipe_specification {
  width: 150px;
}
.el-table__column--pipe_value {
  width: 150px;
}
.el-table__column--pipe_material {
  width: 120px;
}
.el-table__column--pipe_number {
  width: 120px;
}
.el-table__column--pipe_remark {
  width: 200px;
}
.el-table__column--create_time,
.el-table__column--update_time {
  width: 180px;
}
.el-table__column--operation {
  width: 180px;
}

.el-table th {
  table-layout: fixed;
}

.war-id-row {
  display: flex;
  align-items: center;
  width: 100%;
}
.related-war-name {
  color: #409eff; /* 蓝色强调 */
  font-weight: 500;
}
</style>
